#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTimeEdit>
#include <QMessageBox>
#include <QComboBox>

#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QTimer>
#include <QLabel>
#include <QThread>
#include <QSystemTrayIcon>
#include <QSystemTrayIcon>
#include <QCloseEvent>
#include <QMenu>
#include "AlarmModel.h"
#include <QTime>
#include <QFile>
 #include <QTextStream>
 #include <QDebug>

#include "alarmeventdelegate.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , alarmManager(new AlarmManager(this))
    , systemTray(new SystemTray(this))
{
    ui->setupUi(this);
    setWindowFlags(Qt::FramelessWindowHint | Qt::Window);

    qRegisterMetaType<AlarmEvent>("AlarmEvent");

    // 初始化模型
    model = new AlarmEventTableModel(alarmManager, this);
    ui->detailTable->setModel(model);


    // 配置委托
    AlarmEventDelegate *delegate = new AlarmEventDelegate(this);
    ui->detailTable->setItemDelegate(delegate);

    ui->detailTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 设置列宽自适应
    ui->detailTable->horizontalHeader()->setSectionResizeMode(
                0, QHeaderView::ResizeToContents);  // 时间列自适应
//    ui->detailTable->horizontalHeader()->setSectionResizeMode(
//                1, QHeaderView::ResizeToContents);    // 消息列固定200px
//    ui->detailTable->horizontalHeader()->setSectionResizeMode(
//                2, QHeaderView::ResizeToContents); // 重复规则列
    ui->detailTable->horizontalHeader()->setSectionResizeMode(
                1, QHeaderView::Stretch); // 状态列

    // 初始化托盘图标
    systemTray->showMessage("闹钟启动", "系统已就绪", 3000);
    connect(systemTray, &SystemTray::systemTrayIconActivated, [=](QSystemTrayIcon::ActivationReason reason){
        if(reason == QSystemTrayIcon::DoubleClick) {
            this->show();
        }
    });

    // 连接信号槽
    connect(alarmManager, &AlarmManager::alarmTriggered, this, &MainWindow::handleAlarm);
    connect(ui->addButton, &QPushButton::clicked, this, &MainWindow::onAddAlarm);

    connect(ui->removeButton, &QPushButton::clicked, this, &MainWindow::onRemoveAlarm);

    connect(ui->hideButton, &QPushButton::clicked, [this](){


    QTimer::singleShot(0, this, &MainWindow::hide);  // 延迟隐藏避免闪烁
    });

//    QString exePath = QCoreApplication::applicationDirPath();
    QFile file(":/qss/dark.qss"); // 根据文件路径调整(":/style.qss")，也可以使用绝对/相对路径
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        return;
    }
    QTextStream stream(&file);
    QString qss = stream.readAll();
    file.close();
    // 将qss应用到主窗口或应用程序
    setStyleSheet(qss);
}

MainWindow::~MainWindow() {
    delete ui;
}

void MainWindow::onAddAlarm() {
    // 修正后代码
    QModelIndex parent = QModelIndex(); // 默认父索引
    int newRow = model->rowCount();     // 插入到最后
    ui->detailTable->model()->insertRows(newRow, 1, parent); // 插入单行
}

void MainWindow::onRemoveAlarm() {
    QModelIndex parent = QModelIndex(); // 默认父索引
    int rowToDelete = ui->detailTable->currentIndex().row(); // 删除最后一行
    ui->detailTable->model()->removeRows(rowToDelete, 1, parent); // 删除单行
}

void MainWindow::handleAlarm(const AlarmEvent &event) {
    qDebug() << "MainWindow::handleAlarm";
    systemTray->showMessage(event.message, event.message);
}

void MainWindow::changeEvent(QEvent *event) {
    if (event->type() == QEvent::WindowStateChange) {
        if (isMinimized() && !isMinimizedToTray) {
            QTimer::singleShot(0, this, &MainWindow::hide);  // 延迟隐藏避免闪烁
//            systemTray->showMessage("已隐藏", "窗口已移至系统托盘");
            isMinimizedToTray = true;
        }
    }
    QMainWindow::changeEvent(event);
}

void MainWindow::closeEvent(QCloseEvent *event) {
    if (systemTray->isVisible()) {
        event->ignore();
        hide();
//        systemTray->showMessage("已隐藏", "窗口已移至系统托盘", 1000);
    }
}

// 托盘图标点击事件
void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) {
    if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick) {
        showNormalWindow();
    }
}

// 恢复窗口显示
void MainWindow::showNormalWindow() {
    show();
    activateWindow();
    isMinimizedToTray = false;
}
